package com.example.miaopin.fragment;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.miaopin.MainActivity;
import com.example.miaopin.PhotoUtilChange;
import com.example.miaopin.R;
import com.example.miaopin.utils.Util;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.internal.view.ContextThemeWrapper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.ViewGroup;

public abstract class BaseFragment extends Fragment implements OnClickListener {
	private static final String APP_ID = "1104794063";
	public Context mContext;
	protected LayoutInflater inflater;
	public View view;
	private FragmentManager manager;
	protected static Tencent mTencent;
	private BaseUiListener loginListener;
	private UserInfo mInfo;
	private TextView name;
	private ImageView touxiang;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		this.mContext = getActivity();
		this.inflater = inflater;
		return initview();
	}

	/**
	 * @param id
	 * @return 加载带有主题的fragment布局
	 */
	public View inflater1(int id) {
		View view;
		// 使用ContextThemeWrapper通过目标Theme生成一个新的Context
		Context ctxWithTheme = new ContextThemeWrapper(mContext, R.style.Theme_PageIndicatorDefaults);
		// 通过生成的Context创建一个LayoutInflater
		LayoutInflater localLayoutInflater = inflater.cloneInContext(ctxWithTheme);
		view = localLayoutInflater.inflate(id, null);
		return view;
	}

	/**
	 * @param id
	 * @return 加载不带主题的fragment布局
	 */
	public View inflater2(int id) {
		return inflater.inflate(id, null);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.shard:
			break;

		default:
			break;
		}

	}

	public void login() {
		mTencent = Tencent.createInstance(APP_ID, mContext);
		if (mTencent != null && mTencent.isSessionValid()) {
			updateUserInfo();
		} else if (!mTencent.isSessionValid()) {
			loginListener = new BaseUiListener() {
				@Override
				protected void doComplete(JSONObject values) {
					Log.i("values", "values1" + values);
					initOpenidAndToken(values);
					updateUserInfo();
				}
			};

			mTencent.login(this, "all", loginListener);
		} else {
			mTencent.logout(mContext);
		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				JSONObject response = (JSONObject) msg.obj;
				if (response.has("nickname")) {
					try {
						setTtitle(response.getString("nickname"));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			} else if (msg.what == 1) {
				Bitmap bitmap = (Bitmap) msg.obj;
				setImage(bitmap);
			}

		};

	};

	private void updateUserInfo() {

		IUiListener listener = new IUiListener() {

			@Override
			public void onError(UiError e) {

			}

			@Override
			public void onComplete(final Object response) {
				Log.i("ainio", "aini"+response.toString());
				Message msg = new Message();
				msg.obj = response;
				msg.what = 0;
				mHandler.sendMessage(msg);
				new Thread() {

					@Override
					public void run() {
						JSONObject json = (JSONObject) response;
						if (json.has("figureurl")) {
							Bitmap bitmap = null;
							try {
								bitmap = Util.getbitmap(json.getString("figureurl_qq_2"));
							} catch (JSONException e) {

							}
							Message msg = new Message();
							msg.obj = bitmap;
							msg.what = 1;
							mHandler.sendMessage(msg);
						}
					}

				}.start();
			}

			@Override
			public void onCancel() {

			}
		};
		mInfo = new UserInfo(mContext, mTencent.getQQToken());
		mInfo.getUserInfo(listener);

	}

	private class BaseUiListener implements IUiListener {

		@Override
		public void onComplete(Object response) {
			if (null == response) {
				Util.showResultDialog(mContext, "返回为空", "登录失败");
				return;
			}
			JSONObject jsonResponse = (JSONObject) response;
			if (null != jsonResponse && jsonResponse.length() == 0) {
				Util.showResultDialog(mContext, "返回为空", "登录失败");
				return;
			}
			doComplete((JSONObject) response);

		}

		protected void doComplete(JSONObject values) {

		}

		@Override

		public void onError(UiError e) {

			Log.i("onError:", "code:" + e.errorCode + ", msg:"

			+ e.errorMessage + ", detail:" + e.errorDetail);

		}

		@Override

		public void onCancel() {

			Log.i("onCancel", "");

		}

	}

	public static void initOpenidAndToken(JSONObject jsonObject) {
		try {
			String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
			String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
			String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
			if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
				mTencent.setAccessToken(token, expires);
				mTencent.setOpenId(openId);
			}
		} catch (Exception e) {
		}
	}
/*
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		 super.onActivityResult(requestCode, resultCode, data);
		Log.d("values", "-->onActivityResult " + requestCode + " resultCode=" + resultCode);
		mTencent.onActivityResultData(requestCode, resultCode, data, loginListener);
		if (requestCode == Constants.REQUEST_API) {
			if (resultCode == Constants.RESULT_LOGIN) {
				Tencent.handleResultData(data, loginListener);
			}
		} else if (requestCode == Constants.REQUEST_APPBAR) { // app内应用吧登录
			if (resultCode == Constants.RESULT_LOGIN) {
				Util.showResultDialog(mContext, data.getStringExtra(Constants.LOGIN_INFO), "登录成功");
			}
		}
	}*/

	protected abstract View initview();

	protected abstract void setTtitle(String string);

	protected abstract void setImage(Bitmap bitmap);
}
